<?php

class Moutlets extends CI_Model {

	function Moutlets() {
		parent::__construct();
		$this->load->library('calendar');
		$this->load->model('mmaster');
		$this->load->model('mglobal');
		$this->load->library('serversidedatatables');
	}

	function saveOutlets($outlet_id = "", $proses = "") {
		$this->db->trans_start();

		if ($proses == 'new') {
			$query = $this->getOutletID();
			$outlet_id = $query[0]->sp_mobile_outlet;
			$aoutlet_id = explode(' ', $outlet_id);
			$outlet_id = $aoutlet_id[2];
		}
		else
		$this->saveTerritory($outlet_id, $proses);
		$this->saveOutlet($outlet_id, $proses);
		$this->saveOwnerData($outlet_id, $proses);
		$this->saveOutletData($outlet_id, $proses);
		$this->saveBranding($outlet_id, $proses);
		$this->saveProgram($outlet_id);

		$this->mglobal->saveLog('outlet',$proses,$outlet_id);
		if ($this->db->trans_status() === FALSE)
			$this->db->trans_rollback();
		else
			$this->db->trans_commit();
	}

	function saveTerritory($outlet_id, $proses) {
		$data = array();
		$data['territory_name'] = $this->input->post('outlet_name');
		if ($this->input->post('maintain_name') != '')
			{ $data['user_id'] = $this->input->post('maintain_name'); }
		else {
			$data['user_id'] = NULL;
		}
		$data['updated_by'] = $this->session->userdata('username');
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");

		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $outlet_id))->row();
		$istatus = $query->istatus;

		$this->db->update('t_mtr_territory', $data, array('territory_id' => $query->territory_id));

		if ($proses == 'new'){
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 3; } // Jika datanya lengkap
			else { $data['istatus'] = 0; } // Jika datanya belum lengkap
			// $this->db->update('t_mtr_territory', $data, array('territory_id' => $query->territory_id));
		}
		else {
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 4; } // Jika datanya lengkap
			else { $data['istatus'] = 2; } // Jika datanya belum lengkap
		}
		$territory = $this->db->get_where('t_mtr_territory', array('territory_id' => $query->territory_id))->row();
		$this->db->insert('t_mtr_territory_unapproved', $territory);
		$this->db->update('t_mtr_territory_unapproved', $data, array('territory_id' => $query->territory_id));
		
			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-detail-teritory',$proses,'(header='.$outlet_id.' detail='.$lastId.')');

		// $this->db->update('t_mtr_outlet', $data, array('outlet_id' => $outlet_id));

		// if ($istatus == 0) {
		// 	//dipindahin ke atasnya ?? ngerasa harus update deh anggwa@gmail.com
		// 	//$this->db->update('t_mtr_territory', $data, array('territory_id' => $query->territory_id));
		// } else {
		// 	$territory = $this->db->get_where('t_mtr_territory', array('territory_id' => $query->territory_id))->row();
		// 	$this->db->insert('t_mtr_territory_unapproved', $territory);
		// 	$this->db->update('t_mtr_territory_unapproved', $data, array('territory_id' => $query->territory_id));
		// 	$this->db->update('t_mtr_outlet', array('istatus' => 2), array('outlet_id' => $outlet_id));
		// }
	}

	function saveOutlet($outlet_id, $proses) {
		$data = array();
		$parent_id = $this->moutlets->getTerritory($this->session->userdata('username'))->row()->territory_id;

		if ($proses == 'update') {
			$data['outlet_name'] = $this->input->post('outlet_name');
			$data['address'] = $this->input->post('address');
			$data['city'] = $this->input->post('city');
			$data['eload_number'] = $this->input->post('smart_topup_no');
		}

		$data['province_id'] = $this->input->post('province');
		$data['post_code'] = $this->input->post('post_code');
		$data['phone'] = $this->input->post('outlet_phone');
		$data['business_structure'] = $this->input->post('b_structure');
		$data['outbond_caller_id'] = $this->input->post('outbond_caller');
		$data['created_by'] = $this->session->userdata('username');
		$data['updated_by'] = $this->session->userdata('username');
		$data['eload_number'] = $this->input->post('smart_topup_no');
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");

		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $outlet_id))->row();
		$istatus = $query->istatus;

		if ($proses == 'new'){
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 3; } // Jika datanya lengkap
			else { $data['istatus'] = 0; } // Jika datanya belum lengkap

			$this->db->update('t_mtr_outlet', $data, array('outlet_id' => $outlet_id)); 
		}
		else {
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 4; } // Jika datanya lengkap
			else { $data['istatus'] = 2; } // Jika datanya belum lengkap

			$data['outlet_id'] = $outlet_id;
			$data['territory_id'] = $query->territory_id;
			$this->db->insert('t_mtr_outlet_unapproved', $data);
			$this->db->update('t_mtr_outlet', $data, array('outlet_id' => $outlet_id));

			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-detail-info',$proses,'(header='.$outlet_id.' detail='.$lastId.')');

		}
	}

	function saveOutletData($outlet_id, $proses) {
		$data = array();
		$data['outlet_status'] = $this->input->post('outlet_status');
		$data['outlet_type'] = $this->input->post('outlet_type');
		$data['outlet_size'] = $this->input->post('outlet_size');
		$data['outlet_location'] = $this->input->post('outlet_location');

		if (strlen($this->input->post('employee_num')) > 0) {
			$data['outlet_employee_number'] = $this->input->post('employee_num');
		}

		if (strlen($this->input->post('outlet_lifetime')) > 0) {
			$data['outlet_lifetime'] = $this->input->post('outlet_lifetime');
		}
		$data['outlet_ownership'] = $this->input->post('outlet_ownership');
		$data['outlet_smart_no'] = $this->input->post('smart_no');
		$data['outlet_business_focus'] = $this->input->post('b_focus');
		$data['outlet_customer_type'] = $this->input->post('c_type');
		$data['outlet_size_of_business'] = $this->input->post('sob');
		$data['outlet_is_expansion'] = $this->input->post('is_expansion');
		$data['outlet_building'] = $this->input->post('building');

		if ($data['outlet_is_expansion'] == 1)
			$data['outlet_expansion_package'] = $this->input->post('expansion_pack');
		else
			$data['outlet_expansion_package'] = null;

		$data['outlet_join_lajang'] = $this->input->post('join_lajang');

		if ($data['outlet_join_lajang'] == 1) {
			$data['outlet_lajang_is_reorder'] = $this->input->post('is_reorder');
			if ($data['outlet_lajang_is_reorder'] == 1)
				$data['outlet_lajang_package'] = $this->input->post('lajang_pack');
			else
				$data['outlet_lajang_package'] = null;
		}
		else {
			$data['outlet_lajang_is_reorder'] = null;
			$data['outlet_lajang_package'] = null;
		}

		$data['created_by'] = $this->session->userdata('username');
		$data['updated_by'] = $this->session->userdata('username');
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");

		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $outlet_id))->row();
		$istatus = $query->istatus;
        if ($proses == 'new' || $istatus == 0 || $istatus == 3) {
   //      	echo $proses." ". $istatus;
			// print_r($data); die;
            $this->db->update('t_mtr_outlet_data', $data, array('outlet_id' => $outlet_id));
        }
        else {
            $data['outlet_id'] = $outlet_id;
            $this->db->select("outlet_data_id");
            $data_outlet_data = $this->db->get_where('t_mtr_outlet_data', array('outlet_id' => $outlet_id))->row();
   //          echo $proses." ". $istatus."<br>";
   //          print_r($data_outlet_data);
			// print_r($data)."<br>"; die;
            if ($data_outlet_data) {
            	$data['outlet_data_id'] = $data_outlet_data->outlet_data_id;
            	// $this->db->update('t_mtr_outlet_data_unapproved', $data, array('outlet_id' => $outlet_id));
            	$this->db->update('t_mtr_outlet_data', $data, array('outlet_id' => $outlet_id));
            }
            else {
            	$this->db->insert('t_mtr_outlet_data', $data);
            }
        }

			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-detail-data',$proses,'(header='.$outlet_id.' detail='.$lastId.')');

	}

	function saveOwnerData($outlet_id, $proses) {
		$data = array();
		$data['outlet_id'] = $outlet_id;
		$data['owner_name'] = $this->input->post('name_owner');
		$data['owner_gender'] = $this->input->post('gender');
		$data['owner_birth_place'] = $this->input->post('birth_place');
		//anggwa@gmail.com 20120515 - exception kalau date tidak diisi
		//if (strlen($this->input->post('birth_date')) > 2) {
		$data['owner_birth_date'] = $this->input->post('birth_date');
		//}
		//anggwa@gmail.com 20120515 - exception kalau date tidak diisi
		$data['owner_religion'] = $this->input->post('religion');
		$data['owner_email'] = $this->input->post('email');
		$data['owner_phone'] = $this->input->post('phone');
		$data['owner_identity_type'] = $this->input->post('identity_type');
		$data['owner_identity_number'] = $this->input->post('identity_number');
		$data['created_by'] = $this->session->userdata('username');
		$data['updated_by'] = $this->session->userdata('username');
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");

		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $outlet_id))->row();
		$istatus = $query->istatus;


		if ($proses == 'new') {
			$data['created_by'] = $this->session->userdata('username');
			//$data[ 'created_on' ] = date("Y-m-d H:i:s");
			$this->db->insert('t_mtr_outlet_owner', $data);
		} else {
			if ($istatus == '0' || $istatus == '3')
				$this->db->update('t_mtr_outlet_owner', $data, array('outlet_id' => $outlet_id));
			else {
				// $data['outlet_owner_id'] = $this->db->get_where('t_mtr_outlet_owner', array('outlet_id' => $outlet_id))->row()->outlet_owner_id;
				$data_outlet_owner= $this->db->get_where('t_mtr_outlet_owner', array('outlet_id' => $outlet_id))->row();
				if ($data_outlet_owner) {
					$data['outlet_owner_id'] = $data_outlet_owner->outlet_owner_id;
					$this->db->insert('t_mtr_outlet_owner_unapproved', $data);
				}
				else{
					$this->db->insert('t_mtr_outlet_owner', $data);
				}
			}
		}

			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-detail-owner',$proses,'(header='.$outlet_id.' detail='.$lastId.')');

	}

	function saveBranding($outlet_id, $proses) {
		$data = array();
		$data['outlet_id'] = $outlet_id;
		$data['branding_status'] = $this->input->post('status_branding');
		$data['full_branding_by'] = $this->input->post('full_branding');
		if ($this->input->post('contract_end'))
			$data['contract_end'] = $this->input->post('contract_end');
		if ($this->input->post('branding_value'))
			$data['branding_value'] = $this->input->post('branding_value');
		$data['created_by'] = $this->session->userdata('username');
		$data['updated_by'] = $this->session->userdata('username');
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");

		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $outlet_id))->row();
		$istatus = $query->istatus;

		if ($proses == 'new') {
			$data['created_by'] = $this->session->userdata('username');
			//$data[ 'created_on' ] = date("Y-m-d H:i:s");
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 3; } // Jika datanya lengkap
			else { $data['istatus'] = 0; } // Jika datanya belum lengkap
			$this->db->insert('t_mtr_outlet_branding', $data);
		} else {
			if ($istatus == 0)
				$this->db->insert('t_mtr_outlet_branding_unapproved', $data);
			else {
				$data_outlet_branding = $this->db->get_where('t_mtr_outlet_branding', array('outlet_id' => $outlet_id))->row();
				if ($data_outlet_branding) {
					// $data['outlet_branding_id'] = $this->db->get_where('t_mtr_outlet_branding', array('outlet_id' => $outlet_id))->row()->outlet_branding_id;
					$data['outlet_branding_id'] = $data_outlet_branding->outlet_branding_id;
					$this->db->update('t_mtr_outlet_branding', $data, array('outlet_id' => $outlet_id));
				}
				else {
					$this->db->insert('t_mtr_outlet_branding', $data);
				}
				// $this->db->insert('t_mtr_outlet_branding_unapproved', $data);
			}
		}

			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-detail-branding',$proses,'(header='.$outlet_id.' detail='.$lastId.')');

	}

	function saveFrontliners($id, $proses) {
		$data = array();

		$data['frontliner_type'] = $this->input->post('front_type');
		$data['frontliner_name'] = $this->input->post('front_name');
		$data['frontliner_birth_place'] = $this->input->post('front_birth_place');
		$data['frontliner_birth_date'] = $this->input->post('front_birth_date');
		$data['frontliner_identity_type'] = $this->input->post('front_identity_type');
		$data['frontliner_identity_no'] = $this->input->post('front_identity_no');
		$data['frontliner_religion'] = $this->input->post('front_religion');
		$data['frontliner_work_experience'] = intval($this->input->post('front_work_experience'));
		$data['frontliner_marital_status'] = $this->input->post('front_marital_status');
		$data['frontliner_address'] = nl2br($this->input->post('front_address'));
		$data['frontliner_city'] = $this->input->post('front_city');
		$data['frontliner_province_id'] = $this->input->post('front_province');
		$data['frontliner_zip_code'] = $this->input->post('front_zip_code');
		$data['frontliner_mdn_smartfren'] = $this->input->post('front_mdn_smartfren');
		$data['frontliner_remark'] = $this->input->post('front_description');
		$data['updated_by'] = $this->session->userdata('username');
		//$data[ 'updated_on' ] = date("Y-m-d H:i:s");
		if ($proses == 'new') {
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 3; } // Jika datanya lengkap
			else { $data['istatus'] = 1; } // Jika datanya belum lengkap
			$data['outlet_id'] = $id;
			$data['created_by'] = $this->session->userdata('username');
			//$data[ 'created_on' ] = date("Y-m-d H:i:s");
			$this->db->insert('t_mtr_outlet_frontliner', $data);
		} else {
			if ($this->input->post('isDataComplete') == 1) 
				 { $data['istatus'] = 4; } // Jika datanya lengkap
			else { $data['istatus'] = 2; } // Jika datanya belum lengkap
			$temp = $this->db->get_where('t_mtr_outlet_frontliner', array('outlet_frontliner_id' => $id))->row();
			$this->db->update('t_mtr_outlet_frontliner_unapproved', $data);
			$this->db->insert('t_mtr_outlet_frontliner_unapproved', $temp);
			$id = $this->db->get_where('t_mtr_outlet_frontliner', array('outlet_frontliner_id' => $id))->row()->outlet_id;
		}

		// $lastId = $this->db->insert_id();
		// $this->db->update('t_mtr_outlet', array('istatus' => 2), array('outlet_id' => $id));

		$this->mglobal->saveLog('outlet-detail-frontliner',$proses,'(header='.$outlet_id.' detail='.$lastId.')');

	}

	function getOutlet($outletId) {
		$dblokal = $this->load->database("default", TRUE);

		$dblokal->select('*');
		$dblokal->from("t_mtr_territory");
		$dblokal->join("t_mtr_outlet", "t_mtr_outlet.territory_id = t_mtr_territory.territory_id ");
		$dblokal->where(array('outlet_id' => $outletId));
		$dblokal->limit(1, 0);
		$query = $dblokal->get();

		if ($query->num_rows() > 0) {
			return $query->result_array();
		} else {
			return array();
		}
	}

	//by: alfin akhret
	function update_message($user_id, $msg_from, $msg_to, $msg_subject)
	{	

		//cari user name dari si pengirim pesan (yg aproove outlet)
		$this->db->select('user_name');
		$query = $this->db->get_where('t_mtr_user', array('user_id' => $user_id));
		$username = '';

		foreach ($query->result() as $r) 
		{
			$username = $r->user_name;	
		}
		
		$msg_body = "Outlet " .$msg_to ." telah disetujui oleh ". $username; //letakan nama pengirim pada bagian body text
		// echo $msg_body;die();

		//cari user_id recipient
		$this->db->select('territory_id');
		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $msg_to));
		foreach ($query->result() as $r) 
		{
			$territory_id = $r->territory_id;
			$this->db->select('user_id');
			$query2 = $this->db->get_where('t_mtr_territory', array('territory_id' => $territory_id));
			foreach ($query2->result() as $r2) 
			{
				$msg_to = $r2->user_id;	
			}	
		}

		if(($msg_to != null) || ($msg_to != ''))
		{
			$data = array(
					'msg_from' => $msg_from,
					'msg_to' => $msg_to,
					'msg_subject' => $msg_subject,
					'msg_body' => $msg_body,
					'created_by' => $user_id 
				);

			$this->db->insert('t_msg', $data);
		}
	}

	function updateOutlet($id) {

		$this->db->update('t_mtr_outlet', array('istatus' => '1'), array('outlet_id' => $id));

		/**
		 * sementara yg penting masuk JC dulu ini outlet baru 
		 * 20120521 anggwa@gmail.com
		 */
		$r = $this->getOutlet($id);
		$salesId = $r[0]['user_id'];

		$cekTabel = $this->db->get_where('information_schema.tables', array('table_type' => 'BASE TABLE', 'table_name' => 't_jc_' . $salesId));

		if ($cekTabel->num_rows() != 0) {
			$query = $this->db->get_where('t_jc_' . $salesId, array('channel_id' => $id, 'yyyymm' => date('Ym')));
			if ($query->num_rows() == 0) {
				$data = array("parent_id" => $r[0]['territory_id'],
					"yyyymm" => date('Ym'),
					"channel_id" => $r[0]['outlet_id'],
					"created_by" => $this->session->userdata("username")
//                "created_on" => date("Y-m-d H:i:s")
				);
				$this->db->trans_start();
				$this->db->insert('t_jc_' . $salesId, $data);
				$this->mglobal->saveLog('outlet-update','journey-cycle',('channel='.$id.'sfa='.$salesId));
				if ($this->db->trans_status() === FALSE)
					$this->db->trans_rollback();
				else
					$this->db->trans_commit();
			}

		}

//            $ref_id = $this->db->insert_id();
//            $this->mglobal->saveLog('JC_SFA_ADD_JOURNEY_' . "t_jc_" . $sfa, 'insert', $ref_id);
//        }
		// $this->db->trans_start();
		// $query = $this->db->get_where( 't_mtr_outlet_unapproved', array( 'outlet_id' => $id ) );
		// if( $query->num_rows() != 0 )
		// {
		// $arr = $query->row();
		////--$this->db->delete( 't_mtr_outlet', array( 'outlet_id' => $id ) );
		// $this->db->update( 't_mtr_outlet', $arr, array( 'outlet_id' => $id ) );
		// $tr_id = $arr->territory_id;
		// $query = $this->db->get_where( 't_mtr_territory_unapproved', array( 'territory_id' => $tr_id ) );
		// $arr = $query->row();
		// $this->db->update( 't_mtr_territory', $arr, array( 'territory_id' => $tr_id ) );
		// $query = $this->db->get_where( 't_mtr_outlet_data_unapproved', array( 'outlet_id' => $id ) );
		// $arr = $query->row();
		// $this->db->update( 't_mtr_outlet_data', $arr, array( 'outlet_id' => $id ) );
		// $query = $this->db->get_where( 't_mtr_outlet_branding_unapproved', array( 'outlet_id' => $id ) );
		// $arr = $query->row();
		// $this->db->update( 't_mtr_outlet_branding', $arr, array( 'outlet_id' => $id ) );
		// $query = $this->db->get_where( 't_mtr_outlet_owner_unapproved', array( 'outlet_id' => $id ) );
		// $arr = $query->row();
		// $this->db->update( 't_mtr_outlet_owner', $arr, array( 'outlet_id' => $id ) );
		// $this->db->delete( 't_mtr_territory_unapproved', array( 'territory_id' => $tr_id ) );
		// $this->db->delete( 't_mtr_outlet_unapproved', array( 'outlet_id' => $id ) );
		// $this->db->delete( 't_mtr_outlet_data_unapproved', array( 'outlet_id' => $id ) );
		// $this->db->delete( 't_mtr_outlet_branding_unapproved', array( 'outlet_id' => $id ) );
		// $this->db->delete( 't_mtr_outlet_owner_unapproved', array( 'outlet_id' => $id ) );
		// }
		// else
		// {
		// $query = $this->db->get_where( 't_mtr_outlet_frontliner_unapproved', array( 'outlet_id' => $id ) )->row();
		// if( $query != null )
		// {
		// $front_id = $query->outlet_frontliner_id;
		// $istatus = $query->istatus;
		// if( $istatus == 0 )
		// {
		// $this->db->insert( 't_mtr_outlet_frontliner', $query );
		// $this->db->update( 't_mtr_outlet_frontliner', array( 'istatus' => 1 ), array( 'outlet_frontliner_id' => $front_id ) );
		// }
		// else if( $istatus == 2 )
		// {
		// $this->db->update( 't_mtr_outlet_frontliner', $query, array( 'outlet_frontliner_id' => $front_id ) );
		// $this->db->update( 't_mtr_outlet_frontliner', array( 'istatus' => 1 ), array( 'outlet_frontliner_id' => $front_id ) );
		// }
		// else
		// {
		// $this->db->insert( 't_mtr_outlet_frontliner', $query );
		// }
		// $this->db->delete( 't_mtr_outlet_frontliner_unapproved', array( 'outlet_frontliner_id' => $front_id ) );
		// }
		// else
		// {
		// $bank_id = $bank_query->bank_account_id;
		// if( $bank_query->istatus == 0 )
		// {
		// $query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'bank_account_id' => $bank_id ) )->row();
		// $this->db->insert( 't_mtr_bank_account', $query );
		// $this->db->update( 't_mtr_bank_account', array( 'istatus' => 1 ), array( 'bank_account_id' => $bank_id ) );
		// }
		// else if( $bank_query->istatus == 2 )
		// {
		// $this->db->update( 't_mtr_bank_account_unapproved', array( 'istatus' => 1 ), array( 'bank_account_id' => $bank_id ) );
		// $query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'bank_account_id' => $bank_id ) )->row();
		// $this->db->update( 't_mtr_bank_account', $query, array( 'bank_account_id' => $bank_id ) );
		// }
		// else
		// {
		// $query = $this->db->get_where( 't_mtr_bank_account_unapproved', array( 'bank_account_id' => $bank_id ) )->row();
		// $this->db->insert( 't_mtr_bank_account', $query );
		// }
		// $this->db->delete( 't_mtr_bank_account_unapproved', array( 'territory_id' => $territory_id ) );
		// }
		// echo $data[ 'istatus' ] = 1;
		// $data[ 'updated_by' ] = $this->session->userdata( 'username' );
		// $data[ 'updated_on' ] = date("Y-m-d H:i:s");
		// $this->db->update( 't_mtr_outlet', $data, array( 'outlet_id' => $id ) );
		// }
	}

	function deleteOutlet($table_type, $id) {
		if ($table_type == 'temp') {
			$tr_id = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $id))->row()->territory_id;
			$this->db->delete('t_mtr_territory_unapproved', array('territory_id' => $tr_id));
			$this->db->delete('t_mtr_outlet_unapproved', array('outlet_id' => $id));
			$this->db->delete('t_mtr_outlet_data_unapproved', array('outlet_id' => $id));
			$this->db->delete('t_mtr_outlet_branding_unapproved', array('outlet_id' => $id));
			$this->db->delete('t_mtr_outlet_owner_unapproved', array('outlet_id' => $id));
			$this->db->delete('t_mtr_outlet_frontliner_unapproved', array('outlet_id' => $id));

			$data['istatus'] = 1;
			$this->db->update('t_mtr_outlet', $data, array('outlet_id' => $id));
		} else {
			$istatus = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $id))->row()->istatus;

			if ($istatus == 0)
				$data['istatus'] = -10;
			else
				$data['istatus'] = -5;

			$this->db->update('t_mtr_outlet', $data, array('outlet_id' => $id));
		}
			$this->mglobal->saveLog('outlet-delete','delete outlet',$id);
	}

	/*
	function getOutlets($kindOfRecord = "", $id = "") {
		//cek status
		if ($id == "") {
			if ($kindOfRecord == 'new')
				$status = 0;
			else if ($kindOfRecord == 'registered')
				$status = 1;
			else
				$status = 2;

			$dbconn = $this->load->database("default", TRUE);
			$userlogin = $this->session->userdata('username');
//            $sql = "SELECT sp_grid_outlet('$userlogin','$status')";
//
//            $sp = $this->db->get_where('t_lock', array('lock_table' => 'sp_grid_outlet'))->row();
//
//            $lockStatus = $status - 1;
//            if ($sp != null)
//                $lockStatus = $sp->lock_session;
//
//            while ($sp != null || $lockStatus != $status - 1) {
//                sleep(2);
//                $sp = $this->db->get_where('t_lock', array('lock_table' => 'sp_grid_outlet'))->row();
//
//                if ($sp != null)
//                    $lockStatus = $sp->lock_session;
//            }
//
//            $this->db->insert('t_lock', array('lock_key' => 'sp_grid_outlet', 'lock_table' => 'sp_grid_outlet', 'lock_session' => $status, 'lock_user' => $userlogin));
////            $dbconn->query($sql);
////            $query = $this->db->get_where('t_grid_outlet', array('user_id' => $userlogin));
//            $this->db->delete('t_lock', array('lock_table' => 'sp_grid_outlet', 'lock_user' => $userlogin));

		   //query
			$query = $dbconn->query("SELECT ot.outlet_id, ot.outlet_name, ot.address, ot.image_path, 1, '$status', lon, lat
									FROM t_mtr_outlet ot
									JOIN t_mtr_territory tr ON ot.territory_id = tr.territory_id
									AND tr.parent_id = f_get_cluster('$userlogin')
									AND territory_type_id = 5
									AND ot.istatus = '$status'
									ORDER BY outlet_name;");
//            $query = $this->db->get();

			
			if ($query->num_rows() > 0) {
				$i = 0;
				foreach ($query->result() as $row) {
					//$path = $this->mmaster->getTerritoryPath( $row->territory_id );
					//$outlet_b_focus = $this->db->get_where( 't_mtr_outlet_data', array( 'outlet_id' => $row->outlet_id ) )->row()->outlet_business_focus;
					$result[$i]->outlet_id = $row->outlet_id;
					$result[$i]->outlet_name = $row->outlet_name;
					//$result[ $i ]->territory_path = $path[ 'path' ];
					$result[$i]->outlet_address = $row->address;
					$result[$i]->image_path = $row->image_path;
					$result[$i]->long = $row->lon;
					$result[$i]->lat = $row->lat;

					//$result[ $i ]->outlet_business_focus = $outlet_b_focus;
					//$result[ $i ]->eload_number = $row->eload_number;
					//$result[ $i ]->maintained_by = $this->mmaster->getMaintainName( $row->territory_id );
					$i++;
				}

				return $result; 
			

			} else {
				return array();
			}
			
		} else {
			return $this->db->get_where('t_mtr_outlet', array('outlet_id' => $id))->row();
		}
	}
	*/

	
	// By : Alfin Akhret
	function getOutlets($kindOfRecord = "", $id = "")
	{
		//cek status
		$user_group=$this->db->query("SELECT user_group_id from t_mtr_user where user_id='".$this->session->userdata('username')."'")->row()->user_group_id;
		
		if ($id == "") 
		{
            if( $kindOfRecord == 'new' ){
                if ($user_group=='4')
                    $flag=3;
                else
                    $flag=0;                
            }else if( $kindOfRecord == 'registered' ){
                $flag=1;
                //$query = $this->db->get_where( 't_mtr_agent', array(  'istatus'=>1 ) )->limit(1);
            }else{
                if ($user_group=='4')
                    $flag=4;
                else
                    $flag=2;
            }
			$cluster=$this->db->query("SELECT f_get_cluster('".$this->session->userdata('username')."') as cluster")->row()->cluster;
			$sIndexColumn = "outlet_id"; //index column untuk kecepatan akses data
			$sTable = "t_mtr_outlet"; //table pertama
			$sTable2 = "t_mtr_territory"; //table kedua
			$defaultOrder = "1"; //default order berdasarkan field yg ada pada $aColumns
			$userlogin = $this->session->userdata('username'); //user credentials
			$aColumns = array("outlet_id", "outlet_name", "address", "user_name", "image_path"); //field2 yg akan ditampilkan pada dataTables
			
			//SQL query 
			$inputQuery =  "
			SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
			FROM   $sTable JOIN $sTable2 ON ".$sTable.".territory_id = ".$sTable2.".territory_id left join t_mtr_user on t_mtr_territory.user_id = t_mtr_user.user_id
			where ".$sTable2.".parent_id = '$cluster'
			AND territory_type_id = 5 
			AND ".$sTable.".istatus = '".$flag."'";
			
			//execute datatables serversideprocess
			return $this->serversidedatatables->executeServerSideProcess($defaultOrder, $flag, $userlogin, $inputQuery, $aColumns, $sIndexColumn);
		}
	}

	

	function deleteFrontliner($id) {
		$temp = $this->db->get_where('t_mtr_outlet_frontliner', array('outlet_frontliner_id' => $id))->row();
		$this->db->insert('t_mtr_outlet_frontliner_unapproved', $temp);
		$this->db->update('t_mtr_outlet_frontliner', array('istatus' => -5), array('outlet_frontliner_id' => $id));

		$this->mglobal->saveLog('outlet-frontliner','delete frontliner (move to temp)',$id);
	}

	function getFrontliners($id) {
		$query = $this->db->get_where('t_mtr_outlet_frontliner', array('outlet_id' => $id, 'istatus' => 1));

		if ($query->result() != null) {
			$i = 0;

			if ($query->num_rows() > 0) {
				foreach ($query->result() as $row) {
					$result[$i]->outlet_frontliner_id = $row->outlet_frontliner_id;
					$result[$i]->outlet_id = $row->outlet_id;
					$result[$i]->name = $row->frontliner_name;
					$result[$i]->type = $row->frontliner_type;
					$result[$i]->address = $row->frontliner_address;
					$result[$i]->city = $row->frontliner_city;
					$result[$i]->birth_place = $row->frontliner_birth_place;
					$result[$i]->birth_date = $row->frontliner_birth_date;
					$result[$i]->description = $row->frontliner_remark;
					$i++;
				}
			}

			$this->db->where('outlet_id = ', $id);
			$this->db->or_where('istatus > ', '-1');
			// $query = $this->db->get('t_mtr_outlet_frontliner_unapproved');

			// if ($query->num_rows() > 0) {
			// 	foreach ($query->result() as $row) {
			// 		$result[$i]->outlet_frontliner_id = $row->outlet_frontliner_id;
			// 		$result[$i]->outlet_id = $row->outlet_id;
			// 		$result[$i]->name = $row->frontliner_name;
			// 		$result[$i]->type = $row->frontliner_type;
			// 		$result[$i]->address = $row->frontliner_address;
			// 		$result[$i]->city = $row->frontliner_city;
			// 		$result[$i]->birth_place = $row->frontliner_birth_place;
			// 		$result[$i]->birth_date = $row->frontliner_birth_date;
			// 		$result[$i]->description = $row->frontliner_remark;
			// 		$i++;
			// 	}
			// }

			if ($i > 0)
				return $result;
			else
				return array();
		}
		else {
			return $this->db->get_where('t_mtr_outlet_frontliner', array('outlet_id' => $id))->row();
		}
	}


	// function getFrontliners($outlet_id) {
	// 	$query = $this->db->get_where('t_mtr_outlet_frontliner', array('outlet_id' => $id, 'istatus' => 1));
	// 	return $query->result();
	// }

	function getOutletID() {
		$outlet_name = $this->input->post('outlet_name');
		$ssales_id = $this->input->post('maintain_name');
		$soutlet_name = $this->input->post('outlet_name');
		$saddress = $this->input->post('address');
		$scity = $this->input->post('city');
		$sbusiness_focus = $this->input->post('b_focus');
		$seload_number = $this->input->post('smart_etopup');

		$dbconn = $this->load->database("default", TRUE);
		$userlogin = $this->session->userdata('username');
		$sql = "SELECT sp_mobile_outlet('#','$ssales_id','$soutlet_name',f_get_cluster('$userlogin'),'$saddress','$scity','$sbusiness_focus','$seload_number','0','0','0')";

		$query = $dbconn->query($sql);
		if ($query->num_rows() > 0) 
			return $query->result();
		else
			return array();
	}

	/**
	 * anggwa@gmail.com 201215 merge models ke moutlets
	 * @param type $field
	 * @return type 
	 */
	function getComboData($field) {
		if ($field == 'building')
			return $this->db->get('v_combo_outlet_type');
		if ($field == 'gender')
			return $this->db->get('v_combo_gender');
		if ($field == 'religion')
			return $this->db->get('v_combo_religion');
		if ($field == 'identity')
			return $this->db->get('v_combo_identity_type');
		if ($field == 'o_status')
			return $this->db->get('v_combo_outlet_status');
		if ($field == 'o_type')
			return $this->db->get('v_combo_tipe_outlet');
		if ($field == 'o_size')
			return $this->db->get('v_combo_outlet_size');
		if ($field == 'o_location')
			return $this->db->get('v_combo_outlet_location');
		if ($field == 'o_ownership')
			return $this->db->get('v_combo_outlet_ownership');
		if ($field == 'b_structure')
			return $this->db->get('v_combo_business_structure');
		if ($field == 'b_focus')
			return $this->db->get('v_combo_business_focus');
		if ($field == 'b_size')
			return $this->db->get('v_combo_size_of_business');
		if ($field == 'c_type')
			return $this->db->get('v_combo_customer_type');
		if ($field == 'l_package')
			return $this->db->get('v_combo_lajang_list');
		if ($field == 'e_package')
			return $this->db->get('v_combo_expansion_list');
		if ($field == 'position')
			return $this->db->get('v_combo_position');
		if ($field == 'full_branding')
			return $this->db->get('v_combo_full_branding_by');
		if ($field == 'outbond') {
			$this->db->select("user_id as member_value, user_name as member_display
					FROM t_mtr_user usr
					JOIN t_mtr_user_group grp
					ON usr.user_group_id = grp.user_group_id
					AND lower(grp.user_group_name) = 'outbound caller'
										AND usr.istatus = 1
					ORDER BY usr.user_name ASC", FALSE);
			$query = $this->db->get();
			return $query;
		}

		if ($field == 'a_status')
			return $this->db->get('v_combo_agent_selling_type');
		if ($field == 'a_type')
			return $this->db->get('v_combo_agent_type');
		if ($field == 'front_type')
			return $this->db->get('v_combo_frontliner_type');
		if ($field == 'marital')
			return $this->db->get('v_combo_marital_status');
	}

	function getRecord($name) {
		return $this->db->get_where($name);
	}

	/*     * ***************************** TAMBAHAN *************************************** */

	function getTerritoryPath($id = "", $type = "cluster") {

//        $tr_type_id = $this->db->get_where('t_mtr_territory_type', array('lower(territory_type_name)' => $type))->row()->territory_type_id;
//        $sign = 1;
//        $result = '';
//
//        $query = $this->getTerritory($id);
//        $row = $query->row();
//        $territory_id = $row->territory_id;
//        $hasil['territory_id'] = $territory_id;
//        $parent_id = $row->parent_id;
//
//        if ($tr_type_id == $row->territory_type_id) {
//            $sign = 2;
//            $result = $row->territory_name;
//        }
//
//        //while( $parent_id != 0 )
//        while ($parent_id > 1) {
//            $query = $this->getParentTerritory($parent_id);
//            $row = $query->row();
//            $parent_id = $row->parent_id;
//
//            if ($sign == 2) {
//                $result = $row->territory_name . ' -> ' . $result;
//            } else if ($tr_type_id == $row->territory_type_id) {
//                $sign = 2;
//                $result = $row->territory_name;
//            }
//
//
//            $territory_id = $row->territory_id;
//        }
//
//        $hasil['path'] = $result;
		$dbconn = $this->load->database("default", TRUE);
		$sql = "SELECT f_get_territory_path(f_get_cluster('$id')) as path, f_get_cluster('$id') as territory_id";
		$query = $dbconn->query($sql);
		if ($query->num_rows() > 0) {
			$row = $query->row();
			//$res = $query->result_array();
			$hasil['territory_id'] = $row->territory_id;
			$hasil['path'] = $row->path;
		} else {
			return array();
		}


		return $hasil;
	}

	function getMaintainName($id = "", $type = "smart fren ambassador") {
		if ($id == "") {
			$login_user = $this->session->userdata('username');
			$this->db->select("* from t_mtr_user_group WHERE lower(user_group_name) = '$type'");
			$query = $this->db->get()->row();

			if ($query != null) {
				$group_id = $query->user_group_id;
                $user_goup_id = $this->db->get_where('t_mtr_user', array('user_id' => $login_user ), 1)->row()->user_group_id;

                $this->db->order_by('user_name', 'asc'); 
                if (($group_id == '8') && ($user_goup_id == '4')) { // Cluster Coordinator
                    $reporting_to = $login_user;
                }
                else {
                    $reporting_to = $this->db->get_where('t_mtr_user', array('user_id' => $login_user ))->row()->reporting_to;
                }

                $query = $this->db->get_where('t_mtr_user', array('user_group_id' => $group_id, 'reporting_to' => $reporting_to, 'istatus' => 1));
            }
			else
				$query = null;

			return $query;
		}
		else {
/*
			$usr_id = $this->db->get_where('t_mtr_territory', array('territory_id' => $id))->row()->user_id;

			if ($usr_id != null) {
				return $this->db->get_where('t_mtr_user', array('user_id' => $usr_id, 'istatus' => 1))->row()->user_name;
			} else {
				return $this->getMaintainName("", $type);
			}
		}
        */
        //Rizki Was Here
        $usr_id = $this->db->get_where('t_mtr_territory', array('territory_id' => $id))->row()->user_id;
            if($usr_id){
            if($user_name=$this->db->get_where('t_mtr_user', array('user_id' => $usr_id))->row()->user_name)
            {
                return $user_name;}
            else
                return "Unmaintained";}
                else
                return "Unmaintained";
	}
}

	function getTerritory($id) {
		//$record = $this->db->get_where('t_mtr_user_territory', array('user_id' => $id))->row();
		//$record = 
		$this->db->SELECT("f_get_cluster('$id') AS territory_id");
		$record = $this->db->get()->row();

		if ($record != null)
			$id = $record->territory_id;

		return $this->db->get_where('t_mtr_territory', array('territory_id' => $id));
	}

	function getParentTerritory($id) {
		$record = $this->db->get_where('t_mtr_user_territory', array('user_id' => $id))->row();

		if ($record != null)
			$id = $record->territory_id;

		return $this->db->get_where('t_mtr_territory', array('territory_id' => $id));
	}

	function getPosition($id = "") {
		$this->db->select("user_group_name FROM t_mtr_user_group grp JOIN t_mtr_user usr ON usr.user_group_id = grp.user_group_id AND usr.user_id = '" . $id . "'");
		$query = $this->db->get();
		return $query;
	}

	function getTerritoryTypeName($name = "") {
		$this->db->select("* FROM t_mtr_territory_type WHERE lower(territory_type_name) = '" . $name . "'");
		return $this->db->get()->row()->territory_type_id;
	}

	function getOutbondCallerName($id) {
		$this->db->get_where('t_mtr_user', array('user_id' => $id));
	}

	function saveBank($id, $proses, $type) {
		$data = array();

		// ambil data dari form
		$data['bank_name'] = $this->input->post('bank_name');
		$data['bank_branch'] = $this->input->post('bank_branch');
		$data['bank_account_name'] = $this->input->post('bank_account_name');
		$data['bank_account_number'] = $this->input->post('bank_account_number');
		$data['updated_by'] = $this->session->userdata('username');
		$data['updated_on'] = date("Y-m-d H:i:s");

		if ($proses == 'new') {
			$query = $this->db->get_where('t_mtr_' . $type, array($type . '_id' => $id))->row();

			$data['territory_id'] = $query->territory_id;
			$data['created_by'] = $this->session->userdata('username');
			$data['created_on'] = date("Y-m-d H:i:s");
			$data['istatus'] = 0;
			$this->db->insert('t_mtr_bank_account_unapproved', $data);
			$this->db->update('t_mtr_' . $type, array('istatus' => 2), array('territory_id' => $query->territory_id));
		} else {
			$data['istatus'] = 2;
			$query = $this->db->get_where('t_mtr_bank_account', array('bank_account_id' => $id))->row();
			$this->db->insert('t_mtr_bank_account_unapproved', $query);
			$this->db->update('t_mtr_bank_account_unapproved', $data, array('bank_account_id' => $id));
			$tr_id = $query->territory_id;
			$this->db->update('t_mtr_' . $type, array('istatus' => 2), array('territory_id' => $tr_id));
		}
	}

	function getBanks($id) {
		$query = $this->db->get_where('t_mtr_outlet', array('outlet_id' => $id, 'istatus' => 1))->row();
		if ($query == null)
			$query = $this->db->get_where('t_mtr_agent', array('agent_id' => $id))->row();

		//kalau $id = id bank 
		if ($query == null) {
			$query = $this->db->get_where('t_mtr_bank_account', array('bank_account_id' => $id))->row();

			return $query;
		} else { //kalau $id = id agent/outlet
			$i = 0;
			$result = array();
			$tr_id = $query->territory_id;

			// ambil dari tabel primer yang sudah disetujui
			//echo $tr_id;
			$query = $this->db->get_where('t_mtr_bank_account', array('territory_id' => $tr_id, 'istatus' => 1));

			if ($query->num_rows() > 0) {
				foreach ($query->result() as $row) {
					$result[$i]->bank_account_id = $row->bank_account_id;
					$result[$i]->name = $row->bank_name;
					$result[$i]->branch = $row->bank_branch;
					$result[$i]->acc_name = $row->bank_account_name;
					$result[$i]->acc_number = $row->bank_account_number;
					$i++;
				}
			}


			// ambil dari tabel unapproved yang istatusnya 0 atau 2 
			$this->db->where('territory_id = ', $tr_id);
			$this->db->or_where('istatus > ', '-1');
			$query = $this->db->get('t_mtr_bank_account_unapproved');
			if ($query->num_rows() > 0) {
				foreach ($query->result() as $row) {
					$result[$i]->bank_account_id = $row->bank_account_id;
					$result[$i]->name = $row->bank_name;
					$result[$i]->branch = $row->bank_branch;
					$result[$i]->acc_name = $row->bank_account_name;
					$result[$i]->acc_number = $row->bank_account_number;
					$i++;
				}
			}

			if ($i > 0)
				return $result;
			else
				return array();
		}
	}

	public function saveProgram($outlet_id) {

		$user_id = $this->session->userdata("username");
		$this->db->delete('t_mtr_channel_program', array('channel_id' => $outlet_id)); 
		$prorgam_id = $this->input->post("program_id");

		foreach ($prorgam_id as $program) {
			$data = array(
				"channel_id" => $outlet_id, 
				"program_id" => $program, 
				"created_by" => $user_id, 
				"updated_by" => $user_id
				);
			// print_r($data); $this->db->trans_rollback(); die();
			$this->db->insert("t_mtr_channel_program", $data );
			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-program', 'update' ,'(header='.$outlet_id.' detail='.$lastId.')');
		}
	}

	public function addNewProgram($program_type_id, $info) { // $program_type_id harus dikirim dari jQuery object button "Simpan"
		$user_id = $this->session->userdata("username");
		$this->db->select(" f_get_cluster( '$user_id') ");
		$cluster = $this->db->get()->row()->f_get_cluster;
		// $caption = $this->input->post("program_name");
		// $description = $this->input->post("program_description");
		$active = $this->input->post("active");

			$data = array(
				"caption" => $info['caption'], 
				"description" => $info['description'], 
				"program_type_id" => $program_type_id,
				"territory_id" => $cluster,
				"created_by" => $user_id,
				"updated_by" => $user_id,
				"istatus" =>1
				);
			// print_r($data); $this->db->trans_rollback(); die();

		$this->db->trans_start();
			$this->db->insert("t_mtr_program", $data );
			$lastId = $this->db->insert_id();
			$this->mglobal->saveLog('outlet-program', 'add/update' ,$lastId);
		if ($this->db->trans_status() === FALSE)
			$this->db->trans_rollback();
		else
			$this->db->trans_commit();
		return $lastId;
	}
}
